<template>
  <q-page class="cc-admin">
    <div class="col bg-white shadow-2 q-pa-md q-ma-sm">
      <q-table flat color="primary" class="cross_table" separator="cell" :columns="columns" :data="list" row-key="id" :pagination.sync="pagination" :visible-columns="group" @request="query" :rows-per-page-options="[10, 20, 50, 100]" selection="multiple" :selected.sync="selected">
        <template v-slot:top="table">
          <div class="row no-wrap full-width">
            <q-input clearable outlined dense placeholder="请输入关键字搜索" class="on-left" @input="query" debounce="500" v-model="key">
              <template #append>
                <q-btn flat round icon="search" color="primary" @click="query" :loading="loading">
                  <q-tooltip>搜索</q-tooltip>
                </q-btn>
              </template>
            </q-input>
            <q-space />
            <div class="q-gutter-xs">
              <table-top-btns label="选择题" modelName="questions" :showAdd="true" :table="table" :selected="selected" :importing="importing" :exporting="exporting" :importExcelUrlFull="importExcelUrlFull" :columns="columns" @groupChange="groupChange" @add="add" @importExcel="importExcel" @exportExcel="exportExcel"
                @showConfirm="showConfirm" />
            </div>
          </div>
        </template>
        <template #body-cell-question="props">
          <q-td :props="props" :auto-width="true">
            <div style="max-width: 800px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">{{ props.row.question }}</div>
          </q-td>
        </template>
        <template #body-cell-opt="props">
          <q-td :props="props" :auto-width="true">
            <q-btn flat round dense color="primary" icon="edit" @click="edit(props.row)"> <q-tooltip>编辑</q-tooltip></q-btn>
            <q-btn flat round dense color="primary" icon="mdi-content-copy" @click="copy(props.row)">
              <q-tooltip>复制</q-tooltip>
            </q-btn>
            <btn-del label="选择题" @confirm="del(props.row)" />
          </q-td>
        </template>
      </q-table>
    </div>
    <q-dialog maximized flat persistent ref="dialog">
      <q-form @submit="submit" class="dialog_card column">
        <h5 class="view_title justify-between q-px-md">
          {{ editType }}选择题
          <q-btn dense outline round icon="clear" size="sm" v-close-popup />
        </h5>
        <q-scroll-area class="col">
          <div class="row q-col-gutter-x-md dialog_form q-pa-md">
            <div class="col-4">
              <q-select v-model="form.categorys" :options="categoryOptions" clearable multiple label="请选择分类" />
            </div>
            <div class="col-12">
              <h5>题目:</h5>
              <q-input outlined dense v-model="form.question" type="text" />
            </div>
            <div class="col-12">
              <h5>A：</h5>
              <q-input outlined dense v-model="form.optionA" type="text" />
            </div>
            <div class="col-12">
              <h5>B：</h5>
              <q-input outlined dense v-model="form.optionB" type="text" />
            </div>
            <div class="col-12">
              <h5>C：</h5>
              <q-input outlined dense v-model="form.optionC" type="text" />
            </div>
            <div class="col-12">
              <h5>D：</h5>
              <q-input outlined dense v-model="form.optionD" type="text" />
            </div>
            <div class="col-12">
              <h5>答案：</h5>
              <q-input outlined dense v-model="form.answer" type="text" />
            </div>
            <div class="col-12">
              <h5>解析：</h5>
              <q-input outlined dense v-model="form.analysis" type="textarea" />
            </div>
            <div class="col-12">
              <div class="col-12" v-if="!form.viedoUrl">
                <h5>文件上传：</h5>
                <q-uploader url="http://127.0.0.1:9008/weather-api/upload" :headers="headers" field-name="uploadFile" label="文件上传" @uploaded="uploadResult" color="purple" square flat bordered style="max-width: 300px" />
              </div>
              <div style="display: flex; align-items: center">
                <div class="q-video" style="margin-top: 10px" v-if="form.viedoUrl">
                  <viewer class="label-list q-mb-sm" style="max-height: 100px" ref="viewer" :options="options" :image="form.viedoUrl" v-if="form.viedoUrl" @inited="inited">
                    <img class="q-pl-sm" :src="form.viedoUrl" style="object-fit: contain; max-height: 100%; max-width: 150px" />
                  </viewer>
                </div>
                <div class="" style="margin-top: 10px">
                  <q-btn color="primary" icon="mdi-delete" label="删除" outline class="q-mx-md" @click="delVideo" v-if="form.viedoUrl" />
                </div>
              </div>
            </div>
            <div style="display: flex" class="col-12">
              <div class="col-12" v-if="!form.viedoUrl2">
                <h5>解析文件上传：</h5>
                <q-uploader url="http://127.0.0.1:9008/weather-api/upload" :headers="headers" field-name="uploadFile" label="文件上传" @uploaded="uploadResult2" color="purple" square flat bordered style="max-width: 300px" />
              </div>
              <div style="display: flex; align-items: center">
                <div class="q-video" style="margin-top: 10px" v-if="form.viedoUrl2 && imageExtensions.includes(form.viedoUrl2.substring(form.viedoUrl2.lastIndexOf('.')))">
                  <viewer class="label-list q-mb-sm" style="max-height: 100px" ref="viewer" :options="options" :image="form.viedoUrl2" v-if="form.viedoUrl2" @inited="inited">
                    <img class="q-pl-sm" :src="form.viedoUrl2" style="object-fit: contain; max-height: 100%; max-width: 150px" />
                  </viewer>
                </div>
                <div class="q-video" style="margin-top: 10px" v-else>
                  <iframe :src="form.viedoUrl2" frameborder="0" allowfullscreen height="100%" :ratio="4 / 3" />

                </div>
                <div class="" style="margin-top: 10px">
                  <q-btn color="primary" icon="mdi-delete" label="删除" outline class="q-mx-md" @click="delVideo2" v-if="form.viedoUrl2" />
                </div>
              </div>
            </div>
          </div>
        </q-scroll-area>
        <div class="row justify-center q-pa-md">
          <q-btn outline color="primary" icon="mdi-close-thick" label="关闭" v-close-popup />
          <q-btn class="q-mx-md" color="primary" icon="mdi-check-bold" label="提交" :loading="loading" type="submit" />
        </div>
      </q-form>
    </q-dialog>
    <confirm ref="confirmDialog" :msg="confirmMsg" @confirm="deleteBatch()" />
    <q-inner-loading :showing="loading">
      <q-spinner-gears size="50px" color="primary" />
    </q-inner-loading>
  </q-page>
</template>

<script>
import { IndexMixin } from 'boot/mixins';
import { getDictLabel } from 'boot/dictionary';
import confirm from 'components/confirm';
import Viewer from 'viewerjs';

export default {
  name: 'ChoiceQuestions',
  mixins: [IndexMixin],
  components: {
    confirm,
  },
  data() {
    return {
      catalog: '0102',

      categoryOptions: [
        { label: '计算机系统概述', value: '1' },
        { label: '数据的表示和运算', value: '2' },
        { label: '存储器层次结构', value: '3' },
        { label: '指令系统', value: '4' },
        { label: '中央处理器（CPU）', value: '5' },
        { label: '总线', value: '6' },
        { label: '输入输出系统', value: '7' },
      ],
      fileMd5: '',
      showVideo: false,
      fileResult: '',
      form: {
        subjectId: '01',
        subjectText: '计算机',
        majorId: '0102',
        majorText: '计算机组成原理',
        categorys: [],
        categoryIds: '',
        categoryIdsText: '',
        question: '',
        optionA: '',
        optionB: '',
        optionC: '',
        optionD: '',
        answer: '',
        analysis: '',
        viedoUrl: '',
        viedoUrl2: '',
      },
      emptyForm: {
        subjectId: '01',
        subjectText: '计算机',
        majorId: '0102',
        majorText: '计算机组成原理',
        categorys: [],
        categoryIds: '',
        categoryIdsText: '',
        question: '',
        optionA: '',
        optionB: '',
        optionC: '',
        optionD: '',
        answer: '',
        analysis: '',
        viedoUrl: '',
        viedoUrl2: '',
      },
      columns: [
        {
          name: 'index',
          align: 'center',
          label: '序号',
          field: 'index',
        },
        {
          name: 'question',
          align: 'left',
          label: '问题',
          field: 'question',
        },
        {
          name: 'answer',
          align: 'left',
          label: '答案',
          field: 'answer',
        },
        {
          name: 'opt',
          align: 'center',
          label: '操作',
          field: 'id',
        },
      ],
      showQuery: true,
      // headers: [{ name: 'Authorization', value: localStorage.Authorization }],
      uploadUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/upload`,
      imgUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/static`,
      url: {
        list: '/choice/questions/list',
        add: '/choice/questions/add',
        edit: '/choice/questions/edit',
        copy: '/choice/questions/copy',
        delete: '/choice/questions/delete',
        deleteBatch: '/choice/questions/deleteBatch',
        exportXlsUrl: '/choice/questions/exportXls',
        importExcelUrl: '/choice/questions/importExcel',
      },
    };
  },
  methods: {
    exportExcel(fileName) {
      if (!fileName || typeof fileName !== 'string') {
        fileName = '导出文件';
      }
      this.exporting = true;
      console.log(this.selected);
      this.$downFile(this.url.exportXlsUrl, {

        choiceQuestions: this.selected.map((item) => item.id).join(','),
        key: this.key,
        catalog: this.catalog,

      }).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败');
          return;
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), `${fileName}.xls`);
        } else {
          const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }));
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', `${fileName}.xls`);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载完成移除元素
          window.URL.revokeObjectURL(url); // 释放掉blob对象
        }
      }).finally(() => {
        this.exporting = false;
      });
    },

    getDictLabel,
    initDict() { },
    uploadResult(info) {
      const fileResult = JSON.parse(info.xhr.response);
      this.fileResult = fileResult;
      this.form.viedoUrl = `http://127.0.0.1:9000${fileResult.url}`;

      this.showVideo = true;
    },
    uploadResult2(info) {
      const fileResult2 = JSON.parse(info.xhr.response);
      this.fileResult2 = fileResult2;
      this.form.viedoUrl2 = `http://127.0.0.1:9000${fileResult2.url}`;
      console.log(this.form);

      this.showVideo2 = true;
    },
    delVideo2() {
      console.log(this.form.viedoUrl2);
      this.$axios
        .post(`${process.env.SERVER_URL}${process.env.BASE_URL}/deleteVideo`, {
          url: this.form.viedoUrl2,
        })
        .then((r) => {
          this.$info(r.module);
          this.form.viedoUrl2 = '';
        });
    },
    delVideo() {
      console.log(this.form.viedoUrl);
      this.$axios
        .post(`${process.env.SERVER_URL}${process.env.BASE_URL}/deleteVideo`, {
          url: this.form.viedoUrl,
        })
        .then((r) => {
          this.$info(r.module);
          this.form.viedoUrl = '';
        });
    },
  },
  mounted() {
    this.initDict();
  },
};
</script>

<style lang="stylus">
label
  span
    margin-top 10px
img
  width 100%
  height auto
  aspect-ratio 16/9
</style>
